<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.sql.Connection.*" %>
<%@ page import="java.sql.ResultSet.*" %>
<%@ page import="java.sql.SQLException.*" %>
<%@ page import="java.sql.Statement.*" %>
<%@ page import="java.util.ArrayList.*" %>
<%@ page import="java.util.Collection.*" %>
<%@ page import="java.util.Iterator.*" %>
<%@ page import="org.apache.commons.logging.Log.*" %>
<%@ page import="org.apache.commons.logging.LogFactory.*" %>
<%@ page import="org.exolab.castor.jdo.Database.*" %>
<%@ page import="org.exolab.castor.jdo.PersistenceException.*" %>
<%@ page import="org.mbari.vars.dao.IDataObject.*" %>
<%@ page import="org.mbari.vars.dao.ObjectDAO.*" %>
<%@ page import="org.mbari.vars.knowledgebase.model.*" %>
<%@ page import="org.mbari.vars.knowledgebase.model.Concept.*" %>
<%@ page import="org.mbari.vars.knowledgebase.model.ConceptDelegate.*" %>
<%@ page import="org.mbari.vars.knowledgebase.model.ConceptName.*" %>
<%@ page import="org.mbari.vars.knowledgebase.model.dao.*" %>
<%@ page import="org.mbari.vars.dao.*" %>

<%
  StringBuffer debugMessage = new StringBuffer();
  String tab = request.getParameter( "tab" );
  if( tab == null ) {
    Enumeration servletAttributes = session.getAttributeNames();
    while (servletAttributes.hasMoreElements()) {
      String name = (String) servletAttributes.nextElement();
      session.removeAttribute( name );
      debugMessage.append( name + " removed<br>\r\n" );
    }
    tab = new String( "search" );
  } else {
    Enumeration servletParameters = request.getParameterNames();
    while (servletParameters.hasMoreElements()) {
      String name = (String) servletParameters.nextElement();
      session.setAttribute( name, request.getParameter( name ) );
      debugMessage.append( name + " added<br>\r\n" );
    }
  }
  String searchName = (String) request.getParameter( "searchName" );
  String nameToFind = (String) session.getAttribute( "nameToFind" );
  if ( searchName != null ) {
    if ( searchName.equals( "null" ) ) {
      searchName = null;
    } else {
      nameToFind = searchName;
      session.setAttribute( "nameToFind", nameToFind );
    }
  }
  if ( searchName == null ) {
    searchName = nameToFind;
  }
  
  String selectedFromName = null;
  String listName = null;
  Vector sideBarVector = (Vector) session.getAttribute( "sideBarVector" );
  Vector prevFinds = (Vector) session.getAttribute( "prevFinds" );
  String primaryName = null;
  String idName = null;
  Collection<LWConceptName> matches = null;
  String errorMessage = null;

  String nameToOpen = (String) session.getAttribute( "nameToOpen" );
  if ( nameToOpen != null ) {
    if ( nameToOpen.equals( "null" ) ) {
      nameToOpen = null;
    }
  }

%>
<%!

 public Collection<String> writeList ( String primaryName, String idName, String[] cNamesArray, String rankLevel, String rankName ) {
   StringBuffer thisList = new StringBuffer( "" );
   Vector listVector = new Vector( );

   if( rankLevel != null ) {
     if( !rankLevel.equals( "null" ) )
       thisList.append( "&nbsp;" + rankLevel );
   }
   if( rankName != null ) {
     if( !rankName.equals( "null" ) )
       thisList.append( "&nbsp;" + rankName );
   }

   String primaryIdName = new String( idName );
   thisList.append( "&nbsp;<a href=\"DeepSeaGuide.jsp?view=tree&nameToFind=" + primaryName + "\">" + primaryName + "</a>" );
   thisList.append( "\r\n    <ul>" );
   listVector.add( thisList.toString() );
   if ( cNamesArray != null ) {
     int listLength = cNamesArray.length; 
     for ( int i=0; i<listLength; i++ ) {
       idName = cNamesArray[i];
       if ( cNamesArray[i].indexOf( " (" ) > 0 ) {
         idName = cNamesArray[i].substring( 0, cNamesArray[i].indexOf( " (" ) );
       }
       listVector.add( "  <li id=\"" + idName + "\">" );
       listVector.add( "    <a href=\"DeepSeaGuide.jsp?tab=tree&nameToFind=" + idName + "\">" + cNamesArray[i] + "</a></li>" );
     }
     listVector.add( "    </ul></li>  <!--<li id=\"" + primaryIdName + "\">-->" );
   }

   return (Collection<String>) listVector;

 }
%>
<%!
 public Vector getDescendants (Concept parent, String pName, int level) {
   Collection<Concept> children = parent.getChildConceptColl();
   
   if ( children.isEmpty() )
     return null;

   StringBuffer thisLink = new StringBuffer( "<option value=\"\">Select " + pName + "</option>" );

   Vector foundName = new Vector();
   String cName = null;

   for ( Concept child : children ) {
     cName = child.getPrimaryConceptNameAsString();
     if ( cName != null ) {
       Collection<ConceptName> names = child.getConceptNameColl();
       for ( ConceptName name : names ) {
         if( name.getNameType().equals( ConceptName.NAMETYPE_COMMON ) ) {
           cName = cName + " (" + name.getName() + ")";
         }      
       }
       foundName.addElement( cName );     
       if ( level < 1 ) {
         Vector gcNames = getDescendants( child, cName, level + 1 );
         if ( gcNames != null ) {
           foundName.addAll( gcNames );
         }
       }
     }
   }      
   return foundName; 
 }
%>
<%!
  private File
  createExternalHtmlFile ( String htmlFileName )
  throws Exception
  {
    File htmlFile = null;
    boolean fileExists;
    boolean fileWasCreated;
    String canNotCreate
      = "OracleLogonInfo.ini does not exist and can not be created.";
    

    try
    {
      htmlFile = new File ( (String)System.getProperty("catalina.home") + File.separator + "webapps" + File.separator + "test" + File.separator + htmlFileName + ".htm" );
      fileExists = htmlFile.exists ();
      if ( !fileExists )
      {
        fileWasCreated = htmlFile.createNewFile ();
        if ( !fileWasCreated )
          throw (new Exception (canNotCreate) );
      }
    }
    catch (Exception e)
    {
      throw (e);
    }
    return htmlFile;
  }
%>


<html>

<head>
<title>Chained Selects</title>

<script type="text/javascript" src="assets/javascripts/interior.js"></script>
<link rel="stylesheet" type="text/css" href="assets/styles/interior.css">
<link rel="stylesheet" type="text/css" href="styles/interiorVolc.css">
<link rel="stylesheet" type="text/css" href="assets/styles/print.css" media="print">


<%
   String kingdomName   = null; 
   String phylumName    = null;
   String className     = null;
   String subclassName  = null;
   String orderName     = null;
   String suborderName  = null;
   String familyName    = null;
   String subfamilyName = null;
   String genusName     = null;
   String speciesName   = null;


   String[] kingdomArray     = null; 
   String[] phylumArray      = null; 
   String[] classArray       = null; 
   String[] subclassArray    = null; 
   String[] orderArray       = null; 
   String[] suborderArray    = null; 
   String[] familyArray      = null; 
   String[] subfamilyArray   = null; 
   String[] genusArray       = null; 
   String[] speciesArray     = null; 

   try {

      listName = null;
      errorMessage = null;
      debugMessage = new StringBuffer();

      if ( nameToFind == null ) {
        nameToFind = "eukaryota"; 
        if ( searchName != null ) {
          nameToFind = searchName; 
        }
      }
      debugMessage.append( "Finding: " + nameToFind );

      selectedFromName = (String) session.getAttribute( "selectedFromName" );

      if ( selectedFromName != null ) {
        if ( selectedFromName.equals( "null" ) ) {
          selectedFromName = null;
        } else {
          session.setAttribute( selectedFromName + "Name", nameToFind );
        }
        //debugMessage.append( "<br>selectedFromName is not null" );
      }

      debugMessage.append( "<br>selectedFromName: " + selectedFromName );
      if ( selectedFromName == null ) {
        listName = "kingdom"; 
        debugMessage.append( "<br>removing session variable kingdomName" );
        session.removeAttribute( "kingdomName" );
      } else
      if ( selectedFromName.equals( "kingdom" ) ) {
        session.setAttribute( "kingdomName", nameToFind );
        listName = "phylum"; 
        debugMessage.append( "<br>removing session variable phylumName" );
        session.removeAttribute( "phylumName" );
      } else
      if ( selectedFromName.equals( "phylum" ) ) {
        session.setAttribute( "phylumName", nameToFind );
        listName = "class"; 
        debugMessage.append( "<br>removing session variable className" );
        session.removeAttribute( "className" );
      } else
      if ( selectedFromName.equals( "class" ) ) {
        session.setAttribute( "className", nameToFind );
        listName = "subclass"; 
        debugMessage.append( "<br>removing session variable subclassName" );
        session.removeAttribute( "subclassName" );
      } else
      if ( selectedFromName.equals( "subclass" ) ) {
        session.setAttribute( "subclassName", nameToFind );
        listName = "order"; 
        debugMessage.append( "<br>removing session variable orderName" );
        session.removeAttribute( "orderName" );
      } else
      if ( selectedFromName.equals( "order" ) ) {
        session.setAttribute( "orderName", nameToFind );
        listName = "suborder"; 
        debugMessage.append( "<br>removing session variable suborderName" );
        session.removeAttribute( "suborderName" );
      } else
      if ( selectedFromName.equals( "suborder" ) ) {
        session.setAttribute( "suborderName", nameToFind );
        listName = "family"; 
        debugMessage.append( "<br>removing session variable familyName" );
        session.removeAttribute( "familyName" );
      } else
      if ( selectedFromName.equals( "family" ) ) {
        session.setAttribute( "familyName", nameToFind );
        listName = "subfamily"; 
        debugMessage.append( "<br>removing session variable subfamilyName" );
        session.removeAttribute( "subfamilyName" );
      } else
      if ( selectedFromName.equals( "subfamily" ) ) {
        session.setAttribute( "subfamilyName", nameToFind );
        listName = "genus"; 
        debugMessage.append( "<br>removing session variable genusName" );
        session.removeAttribute( "genusName" );
      } else
      if ( selectedFromName.equals( "genus" ) ) {
        session.setAttribute( "genusName", nameToFind );
        listName = "species"; 
        debugMessage.append( "<br>removing session variable speciesName" );
        session.removeAttribute( "speciesName" );
      } else
      if ( selectedFromName.equals( "species" ) ) {
        session.setAttribute( "speciesName", nameToFind );
        listName = "null";
      }
      debugMessage.append( "<br>listName: " + listName );
      if ( listName != null ) {
        session.setAttribute( listName, nameToFind );
      }

      Concept concept = null;
      primaryName = null;
      idName = nameToFind;
      String[] cNamesArray = (String[]) session.getAttribute( nameToFind + "Array" );
      int found = -1;
      if( prevFinds == null ) {
        prevFinds = new Vector();
      } else {
        found = prevFinds.indexOf( nameToFind );
        debugMessage.append( "\r\n<br>" + nameToFind + " at " + found );
      }
      if ( sideBarVector == null ) {
        found = -1;
        //cNamesArray = null;
      }
      if ( found >= 0 ) {
        concept = (Concept) session.getAttribute( nameToFind );
        matches = (Collection<LWConceptName>) session.getAttribute( idName + "Matches" );
        primaryName = concept.getPrimaryConceptNameAsString( );
        idName = primaryName;
      } else
      if ( found < 0 ) {

        //Starts With or Contains
        IKnowledgeBaseCache cache = KnowledgeBaseCache.getInstance();
        String searchType = (String) session.getAttribute( "searchType" );
        if ( cache != null ) {
          if ( searchType != null ) {
            if( searchType.equals( "contains" ) ) {
              matches = cache.findNamesBySubString( searchName );
              if ( matches != null ) {
                debugMessage.append( "<br>Found " + matches.size() + " results containing " + searchName );
                debugMessage.append( "<br>Writing to: " + (String)System.getProperty("catalina.home") + File.separator + "webapps" + File.separator + "test" + File.separator + searchName + ".htm" );
              }
            } else
            if( searchType.equals( "startsWith" ) ) {
              matches = cache.findNamesStartingWith( searchName );
              if ( matches != null ) {
                debugMessage.append( "<br>Found " + matches.size() + " results starting with " + searchName );
              }
            }
          }
          session.setAttribute( idName + "Matches", matches );
        }

        if ( concept == null ) {
        // Use a DAO Object to fetch a concept by name
          try {
            concept = ConceptDAO.getInstance().findByName( nameToFind );
            if ( concept == null && matches != null) {
              debugMessage.append( "\r\n<br>No Concept for " + nameToFind );
              nameToFind = matches.iterator().next().getName();
              concept = ConceptDAO.getInstance().findByName( nameToFind );
              debugMessage.append( "\r\n<br>Instead found: " + nameToFind );
            }  
            session.setAttribute( nameToFind, concept );
          }
          catch (DAOException ex) {
            // database transaction failed. Handle Exception
            errorMessage = "ConceptDAO Error: " + ex.toString();
          }
        }


        if (concept == null)
          debugMessage.append( "<br>Concept not found." );
        else
        if (concept != null) {
          debugMessage.append( "<br>Found concept for " + nameToFind );
          primaryName = concept.getPrimaryConceptNameAsString( );
          if ( primaryName == null ) {
            debugMessage.append( "<br>primaryName is null" );
          }
          idName = new String( primaryName );
          String displayName = new String( idName );
          if ( !displayName.equalsIgnoreCase( nameToFind ) ) {
            displayName = new String( idName + "(" + nameToFind + ")" );
          }
          prevFinds.add( 0, displayName );
          prevFinds.add( 0, nameToFind );
          session.setAttribute( "prevFinds", prevFinds );

          debugMessage.append( "<br>Primary name is: " + primaryName );
          Concept parentConcept = concept.getParentConcept();
          String parentName = parentConcept.getPrimaryConceptNameAsString();
          debugMessage.append( "<br>Parent: " + parentName );
          //debugMessage.append( "<br>Getting: " + nameToFind + "Array" );

          String rankName = null;
          String rankLevel = null;
          Vector cNames = getDescendants( concept, primaryName, 1 );
          cNamesArray = null;

          if ( cNames != null ) {
            cNamesArray = (String[]) cNames.toArray(new String[0]);
          }
            //debugMessage.append( "<br>Setting: " + primaryName + "Array" );
            //session.setAttribute( primaryName + "Array", cNamesArray );
          

            String thisList = null;
            if ( sideBarVector == null ) {  
            // Create sideBarVector

              sideBarVector = new Vector();
              debugMessage.append( "<br>Create SideBarList for " + primaryName );
              sideBarVector.add( 0, "<UL CLASS=\"mktree\" id=\"tree1\">" );
 
              //Get parents
              while ( parentConcept != null ) {
                parentName = parentConcept.getPrimaryConceptNameAsString();
                rankName = parentConcept.getRankName();
                rankLevel = parentConcept.getRankLevel();
                sideBarVector.addAll( 1, writeList( parentName, parentName, null, rankLevel, rankName ) );
                sideBarVector.add( 1, "  <li id=\"" + parentName + "\">" );
                sideBarVector.add( "    </ul></li>  <!--<li id=\"" + parentName + "\">-->" );
                parentConcept = parentConcept.getParentConcept();
              }
              int parentCount = sideBarVector.size()/3*2+1;

              rankName = concept.getRankName();
              rankLevel = concept.getRankLevel();
              if( cNamesArray == null ) {
                sideBarVector.add( parentCount, "    </ul></li>  <!--<li id=\"" + primaryName + "\">-->" );
              } 
              sideBarVector.addAll( parentCount, writeList( primaryName, idName, cNamesArray, rankLevel, rankName ) );
              //sideBarVector.add( parentCount*2-1, thisList );
              sideBarVector.add( parentCount, "  <li id=\"" + primaryName + "\">" );
              sideBarVector.add( "</UL><br>" );
              debugMessage.append( "<br>Setting sideBarList." );
              session.setAttribute( "sideBarVector", sideBarVector );
            } else {
            //expand sideBarVector

              String liPrimaryName = "  <li id=\"" + idName + "\">";
              //debugMessage.append( "<br>Searching sideBar for: " + idName );
              int primaryNameIndex = sideBarVector.indexOf( liPrimaryName ) + 1;
              //debugMessage.append( "<br>sideBar contains: " + sideBarVector.get( primaryNameIndex ) );
              //debugMessage.append( "<br>Found at: " + primaryNameIndex );
              if ( primaryNameIndex > 0 ) {
  
                debugMessage.append( "<br>Removing: " + primaryNameIndex );
                sideBarVector.removeElementAt( primaryNameIndex );
                String nextId = null;
                if( sideBarVector.size() > primaryNameIndex ) {
                  nextId = (String) sideBarVector.get( primaryNameIndex );
                } else {
                  primaryNameIndex = 999999;
                }

                rankName = concept.getRankName();
                rankLevel = concept.getRankLevel();
                sideBarVector.addAll( primaryNameIndex, writeList( idName, primaryName, cNamesArray, rankLevel, rankName ) );

                debugMessage.append( "\r\n<br>Removing: " + nextId );
                int nextIdIndex = sideBarVector.indexOf( nextId );
                int lastIdIndex = sideBarVector.lastIndexOf( nextId );

                //debugMessage.append( "\r\n<br>Moving : " + lastIdIndex );
                //debugMessage.append( "\r\n<br>to : " + nextIdIndex );
                //debugMessage.append( "\r\n<br>Moving : " + (String) sideBarVector.get( 44 ) );
                //debugMessage.append( "\r\n<br>to : " + (String) sideBarVector.get( 39 ) );
                while( lastIdIndex > nextIdIndex ) {
                  //debugMessage.append( "\r\n<br>Removing: " + sideBarVector.get( nextIdIndex ) );

                  sideBarVector.removeElementAt( nextIdIndex );
                  sideBarVector.removeElementAt( nextIdIndex );

                  int moveElementIndex = lastIdIndex - 2;
                  String moveElement = (String) sideBarVector.get( moveElementIndex );
                  sideBarVector.add( nextIdIndex++, moveElement );
                  sideBarVector.removeElementAt( ++moveElementIndex );
                  moveElement = (String) sideBarVector.get( moveElementIndex );
                  while ( moveElement.indexOf( nextId.substring( 4, nextId.length() ) ) < 0 ) {
                    debugMessage.append( "<br>Moving: " + moveElement );
                    sideBarVector.add( nextIdIndex++, moveElement );
                    sideBarVector.removeElementAt( ++moveElementIndex );
                    if( moveElementIndex < sideBarVector.size() ) {
                      moveElement = (String) sideBarVector.get( moveElementIndex );
                    } else {
                     break; 
                    }
                  }

                  liPrimaryName = "    </ul></li>  <!--<li id=\"" + idName + "\">-->";
                  debugMessage.append( "\r\n<br>Searching sideBar for end of: " + idName );
                  primaryNameIndex = sideBarVector.indexOf( liPrimaryName ) + 1;
                  debugMessage.append( "\r\n<br>sideBar contains: " + sideBarVector.get( primaryNameIndex ) );
                  debugMessage.append( "\r\n<br>Found at: " + primaryNameIndex );

                  if ( primaryNameIndex > 0 ) {
  
                    nextId = null;
                    if( sideBarVector.size() > primaryNameIndex ) {
                      nextId = (String) sideBarVector.get( primaryNameIndex );
                    } else {
                      primaryNameIndex = 999999;
                    }

                    //debugMessage.append( "\r\n<br>Removing: " + nextId );
                    nextIdIndex = sideBarVector.indexOf( nextId );
                    lastIdIndex = sideBarVector.lastIndexOf( nextId );

                    //debugMessage.append( "\r\n<br>Moving : " + lastIdIndex );
                    //debugMessage.append( "\r\n<br>to : " + nextIdIndex );
                    //debugMessage.append( "\r\n<br>Moving : " + (String) sideBarVector.get( 199 ) );
                    //debugMessage.append( "\r\n<br>to : " + (String) sideBarVector.get( 198 ) );
                    if ( nextIdIndex == lastIdIndex - 1 ) {
                      sideBarVector.removeElementAt( nextIdIndex );
                      nextIdIndex = lastIdIndex;
                    }
                    
                  } else {
                    nextIdIndex = lastIdIndex;
                  }

                }
   
              } else {
              //Get parents, then insert into sideBarVector
              debugMessage.append( "\r\n<br>Get parents, then insert into sideBarVector" );
              parentName = parentConcept.getPrimaryConceptNameAsString();
              String liParentName = "  <li id=\"" + parentName + "\">";
              //debugMessage.append( "<br>\r\nSearching sideBar for: " + liParentName );
              Vector parentVector = new Vector();
              while ( sideBarVector.indexOf( liParentName ) < 0 ) {
                if( parentConcept == null ) {
                  break;
                }
                parentName = parentConcept.getPrimaryConceptNameAsString();
                liParentName = "  <li id=\"" + parentName + "\">";
                rankName = parentConcept.getRankName();
                rankLevel = parentConcept.getRankLevel();
                parentVector.addAll( 0, writeList( parentName, parentName, null, rankLevel, rankName ) );
                parentVector.add( 0, liParentName );
                parentVector.add( "  </ul></li>  <!--" + liParentName + "-->" );
                parentConcept = parentConcept.getParentConcept();
              }

              //debugMessage.append( "\r\n<br>Removing " + parentVector.get( parentVector.size()-1 ) + " at (" + parentVector.size() + ")" );
/*
              if( parentVector.size() > 0 ) {
                parentVector.removeElementAt( 0 );
                parentVector.removeElementAt( 0 );
                parentVector.removeElementAt( parentVector.size()-1 );
              }
*/
              int parentCount = parentVector.size()/3*2;
              debugMessage.append( "\r\n<br>" + parentCount + " parents" );


              rankName = concept.getRankName();
              rankLevel = concept.getRankLevel();
debugMessage.append( "\r\n<br>Insert " + primaryName + " at " + parentCount );            

              parentVector.addAll( parentCount, writeList( idName, primaryName, cNamesArray, rankLevel, rankName ) );
              parentVector.add( parentCount, "  <li id=\"" + idName + "\">" );

//parentVector.add( "  </ul></li>  <!--<li id=\"" + idName + "\">-->" );
              debugMessage.append( "\r\n<br>" + parentVector.size() + " elements inserted" );

                parentCount = sideBarVector.indexOf( liParentName );
                //if( parentConcept == null ) {
                //  parentCount = sideBarVector.size()/3*2+1;
                //}

                debugMessage.append( "\r\n<br>Removing " + sideBarVector.get( parentCount ) + " at (" + parentCount + ")" );
                sideBarVector.removeElementAt( parentCount );
                sideBarVector.removeElementAt( parentCount );

                sideBarVector.addAll( parentCount, parentVector );

              }
            }            
            if ( sideBarVector != null ) {
              debugMessage.append( "\r\n<br>sideBarList set." );
              session.setAttribute( "sideBarVector", sideBarVector );
            }

 /*
         if ( cNames == null ) {
            //Concept has no descendants, so forward to ConceptView
            debugMessage.append( "<br>Forwarding to: DSGConceptView.jsp?nameToFind=" + primaryName );
            RequestDispatcher dispatcher = request.getRequestDispatcher( "DSGConceptView.jsp?nameToFind=" + primaryName );
            dispatcher.forward(request, response);                              
          }
 */
       }
      } //found < 0
    } catch (Exception ex) {
      errorMessage = "Test Error: " + ex.toString();
    }

%>

<SCRIPT SRC="mktree.js" LANGUAGE="JavaScript"></SCRIPT> 
<LINK REL="stylesheet" HREF="mktree.css">
</head>

<body onLoad="expandToItem('tree1','<%= idName %>'); return false;">

<table align="center" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr><td colspan=3>
<!--begin whole page table-->
  <table id="pagetable" border="0" cellspacing="0" cellpadding="0" align="center">
  <!--begin header-->
  <tr>
	<td id="header_1" colspan="3" align="center" valign="top"><table id="toplinks" border="0" width="100%" cellspacing="0" cellpadding="0">	
        <tr bgcolor="#336699">
	  <td colspan="9" align="center" valign="top" height="6"><img src="http://www.mbari.org/art/interior_levels/header/header_top.gif" alt="" width="750" height="6" hspace="0" vspace="0" border="0"></td>
        </tr>

        <tr bgcolor="#E1E2D5">
	  <td align="left" valign="top" height="19"><img src="http://www.mbari.org/art/interior_levels/header/links/spacer_left.gif" alt="" width="8" height="19" hspace="0" vspace="0" border="0"></td>
	  <td align="center" valign="top"><a href="/default.htm" onMouseOver="imgOn('link1'); self.status='Return to MBARI homepage'; return true;" onMouseOut="imgOff('link1'); self.status='';"><img src="http://www.mbari.org/art/interior_levels/header/links/home_off.gif" alt="Home" width="85" height="19" hspace="0" vspace="0" border="0" name="link1"></a></td>
	  <td align="center" valign="top"><a href="/news/" onMouseOver="imgOn('link2'); self.status='News and Information about MBARI'; return true;" onMouseOut="imgOff('link2'); self.status='';"><img src="http://www.mbari.org/art/interior_levels/header/links/news_info_off.gif" alt="News and Information" width="126" height="19" hspace="0" vspace="0" border="0" name="link2"></a></td>
	  <td align="center" valign="top"><a href="/moos/" onMouseOver="imgOn('link3'); self.status='Ocean Observatories'; return true;" onMouseOut="imgOff('link3'); self.status='';"><img src="http://www.mbari.org/art/interior_levels/header/links/observatories_off.gif" alt="Ocean Observatories" width="138" height="19" hspace="0" vspace="0" border="0" name="link3"></a></td>
	  <td align="center" valign="top"><a href="/rd/" onMouseOver="imgOn('link4'); self.status='Research and Development'; return true;" onMouseOut="imgOff('link4'); self.status='';"><img src="http://www.mbari.org/art/interior_levels/header/links/r_d_off.gif" alt="Research and Development" width="87" height="19" hspace="0" vspace="0" border="0" name="link4"></a></td>
	  <td align="center" valign="top"><a href="/data/" onMouseOver="imgOn('link5'); self.status='Scientific Data and Images'; return true;" onMouseOut="imgOff('link5'); self.status='';"><img src="http://www.mbari.org/art/interior_levels/header/links/data_off.gif" alt="Data" width="79" height="19" hspace="0" vspace="0" border="0" name="link5"></a></td>
	  <td align="center" valign="top"><a href="/dmo/" onMouseOver="imgOn('link6'); self.status='Marine Operations'; return true;" onMouseOut="imgOff('link6'); self.status='';"><img src="http://www.mbari.org/art/interior_levels/header/links/marine_ops_off.gif" alt="Marine Ops" width="122" height="19" hspace="0" vspace="0" border="0" name="link6"></a></td>
	  <td align="center" valign="top"><a href="/search.htm" onMouseOver="imgOn('link7'); self.status='Search the MBARI website'; return true;" onMouseOut="imgOff('link7'); self.status='';"><img src="http://www.mbari.org/art/interior_levels/header/links/search_off.gif" alt="Search" width="92" height="19" hspace="0" vspace="0" border="0" name="link7"></a></td>
	  <td align="right" valign="top"><img src="http://www.mbari.org/art/interior_levels/header/links/spacer_right.gif" alt="" width="13" height="19" hspace="0" vspace="0" border="0"></td>
        </tr>
  </table>
</td></tr>

<tr>
	<td id="header_2" align="right" valign="top" rowspan="2"><img src="http://www.mbari.org/art/interior_levels/header/mbari_logo_left.gif" alt="" width="140" height="95" hspace="0" vspace="0" border="0"></td>
	<td bgcolor=#fff0eb id="header_3" align="left" valign="top" rowspan="2"><img src="art/interior_levels/header/mbari_logo_right.gif" alt="" width="95" height="95" hspace="0" vspace="0" border="0"></td>
	<td id="header_4" align="right" valign="top" height="42"><img src="art/interior_levels/header/info_field/blank.gif" alt="" width="505" height="42" hspace="0" vspace="0" border="0" name="infofield"></td>
</tr>


<tr>
	<td align="right" valign="top" height="53" width=100%>
          <!--provide section title here -->
          <div id="sectiontitle">Deep Sea Guide</div>     
        </td>
</tr>
<!--end header-->

<!--begin body row-->
<tr>
<!--navbar cell-->
	<td id="navbar_cell" width="150" align="left" valign="top">
	
<!-- *** Server include for volcanism navbar *** -->
<!--navbar section title -->
<div id="navtitle"><a class="navtitle">Deep Sea Guide</a></div>
<br>
<!--begin main navbar links-->
<!--<a href="DeepSeaGuide.jsp">Search Taxonomy</a>-->


<!--begin content cell-->
    <td id="content_cell" align="left" valign="top" colspan="2">
    

<!-- *** begin page content here *** -->
<div id="content" align="left" height=1000px>
<!--/div at the end of the content part-->

<div id="pagebreak" align="center"><br></div>
<!-- *** Server include for header links *** -->
<!--header links-->



<span style="background-color:<%= tab.equals("search") ? "#336699" : "#F4F9F4" %>">
  <A href="DeepSeaGuide.jsp">New Search</A></span>
<span style="background-color:<%= tab.equals("list") ? "#336699" : "#F4F9F4" %>">
  <A href="DeepSeaGuide.jsp?tab=list">Search Results</A></span>
<span style="background-color:<%= tab.equals("tree") ? "#336699" : "#F4F9F4" %>">
  <A href="DeepSeaGuide.jsp?tab=tree">Browse Tree</A></span>
<span style="background-color:<%= tab.equals("class") ? "#336699" : "#F4F9F4" %>">
  <A href="#" onClick="expandTree('tree1'); return false;">Browse Classification</A></span>
<% String view = (String) request.getParameter( "view" ); %>
<% if( view == null ) { %>
  <% view = new String( "null" ); %>
<% } %>
<table align="center" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr><td>
<div id="pagetitle" align="center">Deep Sea Guide Search</div>
<br>
<% if( tab.equals( "tree" ) ) { %>
  <A href="#" onClick="expandTree('tree1'); return false;">Expand All</A>
  <A href="#" onClick="collapseTree('tree1'); return false;">Collapse All</A>
  <br>
  <% if ( prevFinds.size() > 1 ) { %>
    Go&nbsp;to&nbsp;
    <select name="goTo" onchange="collapseTree('tree1'); expandToItem('tree1',       this.options[this.selectedIndex].value );expandtab('maintab', this.selectedIndex);">
    <% for( int i=1; i<prevFinds.size(); i++ ) {  %>
      <% String displayName = (String) prevFinds.get(i); %>
      <% String valueName = new String( displayName); %>
      <% int synonym = displayName.indexOf( "(" ); %>
      <% if ( synonym > 0 ) { %>
        <% valueName = displayName.substring( 0, synonym ); %>
      <% } %>
      <option value="<%= valueName %>"<%= valueName.equals( idName ) ? " selected" : "" %>><%= displayName %></option>
      <% i++; %>
  <% } %>
    </select>
  <% } %>
  <% if ( sideBarVector != null ) {  %>
    <% for( int i=0; i<sideBarVector.size(); i++ ) {  %>
      <%= ((String) sideBarVector.get(i)).replace( ">" + primaryName, "><font color=red>" + primaryName + "</font>" ) %>
    <% } %>
  <% } %>
  <script>
    addEvent(window,"load",expandToItem('tree1','<%= nameToFind %>');
  </script>
<% } %>
<form>
<table border=0 width=100%>
<tr>
<td width=25%>  &nbsp;</td>
<td valign="top">
  <font color=#336699>
  <input
     size=50
     type=text
     id=searchName
     name=searchName
     value="<%= searchName == null ? "Type keyword here" : searchName %>"
     onClick=searchName.select(); />
  <input type=hidden name=tab value=<%= tab.equals("search") ? "list" : tab %> />
  <input type=submit value=Search />
  <br>
  <INPUT TYPE=RADIO NAME="searchType" VALUE="startsWith"/>Starts With
  <INPUT TYPE=RADIO NAME="searchType" VALUE="contains" checked="checked"/>Contains
  <br>
  <b>Extend Search to:</b>
  <br><input name="Parents" type="checkbox" value="Parents">Parent
  <input name="Siblings" type="checkbox" value="Siblings">Siblings
  <input name="Children" type="checkbox" value="Children">Children
  <input name="Descendants" type="checkbox" value="Descendants">Descendants<br>
</td>
<td width=25%>  &nbsp;</td>
</tr>


<% if ( tab.equals( "list" ) ) { %>
  <% if ( matches == null ) { %>
      <tr><td colspan=3 valign="top">No matches for <%= nameToFind %></td></tr>
  <% } else if ( matches != null ) { %>
      <% int numOfMatches = matches.size(); %>
      <tr><td colspan=3 valign="top"><%= numOfMatches %> match(es) for <%= searchName %></td></tr>
    <!--File htmlFile = createExternalHtmlFile( searchName );-->
    <%
    FileOutputStream fileOutputStream = 
      new FileOutputStream (
            (String)System.getProperty("catalina.home") + File.separator + "webapps" + File.separator + "test" + File.separator + idName + ".htm" );
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter ( fileOutputStream );
    BufferedWriter bufferedWriter = new BufferedWriter ( outputStreamWriter );
    bufferedWriter.write ( "<html><body>", 0, 12 );
    bufferedWriter.newLine ();
    %>
    <% if( numOfMatches == 0 ) { %>
      <tr><td colspan=3 valign="top">No matches for <%= searchName %></td></tr>
    <% } else { %>
    <% String bgcolor = "F4F9F4"; %>
    <% for ( LWConceptName match : matches ) { %>
      <% String matchName = match.getName(); %>
      <% String tableRow = "<tr bgcolor=" + bgcolor + "><td><a target=_blank href=\"DSGConceptView.jsp?selectedFromName=None&searchName=" + matchName + "&idName=" + matchName + "\">" + matchName + "</a></td>"; %>
      <%
      bufferedWriter.write ( 
        tableRow, 0, tableRow.length ()
      );
      bufferedWriter.newLine ();
      %><%= tableRow %><%
      Concept matchConcept = ConceptDAO.getInstance().findByName( matchName );
      String matchPrimaryName = matchConcept.getPrimaryConceptNameAsString( );
      if ( matchPrimaryName != null ) {
        tableRow = "<td><a target=_blank href=\"DSGConceptView.jsp?selectedFromName=None&searchName=" + matchPrimaryName + "&idName=" + matchPrimaryName + "\">" + matchPrimaryName + "</a></td>";
      } else {
        tableRow = "  <td>&nbsp;</td>";
      }
      bufferedWriter.write ( 
        tableRow, 0, tableRow.length ()
      );
      bufferedWriter.newLine ();
      %><%= tableRow %><%
      String primaryImageURL = matchConcept.getPrimaryImage();
      if ( primaryImageURL != null ) {
        primaryImageURL = primaryImageURL.replace( "sundog", "sundog.shore.mbari.org" );
        tableRow = "  <td colspan=2><a target=_blank href=\"DSGConceptView.jsp?selectedFromName=None&searchName=" + matchName + "&idName=" + matchName + "\"><img src=\"" + primaryImageURL + "\" width=50px/></a></td></tr>";
      } else {
        tableRow = "  <td>&nbsp;</td></tr>";
      }
      bufferedWriter.write ( 
        tableRow, 0, tableRow.length ()
      );
      bufferedWriter.newLine ();
      %>
      <%= tableRow %>
      <% if ( bgcolor.equals( "F4F9F4" ) ) { %>
        <% bgcolor = "ffffff"; %>
      <% } else { %>
        <% bgcolor = "F4F9F4"; %> 
      <% } %>
    <% } %>
    <%
    bufferedWriter.write ( "</table>", 0, 8 );
    bufferedWriter.newLine ();
    %>
    <% } %>
    <%
    bufferedWriter.write ( "</body></html>", 0, 14 );
    bufferedWriter.close ();
    fileOutputStream.close ();
    %>
  <% } %>
<% } %>
<% if ( errorMessage != null ) { %>
  <font color=red size=5><%= errorMessage %></font>
<% } %>

</div>

</td>
</tr>
</table>

Debug info:<br><%= debugMessage.toString() %>
</body>
</html>